package com.payment.web.controller.app.notify;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.enums.SystemConfigCode;
import com.payment.common.type.MoneyTypeStatus;
import com.payment.common.type.PaymentOrderType;
import com.payment.common.type.PlanItemType;
import com.payment.common.type.SMSTemplateType;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.SignUtil;
import com.payment.common.utils.StringUtils;
import com.payment.common.utils.pay.EncryptUtil;
import com.payment.common.utils.push.JPushUtil;
import com.payment.system.config.GuangGuConfig;
import com.payment.system.domain.*;
import com.payment.system.mapper.*;
import com.payment.system.service.IAcqService;
import com.payment.system.service.ICompanyMoneyChangService;
import com.payment.system.service.IMoneyChangeService;
import com.payment.system.service.impl.WxAliPayServiceImpl;
import com.payment.system.util.GuangGuUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * 光谷 异步回调处理
 *
 * @author 15133
 */

@RestController
@RequestMapping("/app/guangGuNotify")
public class GuangGuNotifyController {
    private static final Logger LOGGER = LoggerFactory.getLogger(GuangGuNotifyController.class);

    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    @Autowired
    private PlanItemNewMapper planItemNewMapper;
    @Autowired
    private PlanNewMapper planNewMapper;
    @Autowired
    private IAcqService acqService;
    @Autowired
    private IMoneyChangeService moneyChangeService;
    @Autowired
    private SystemConfigMapper configMapper;
    @Autowired
    private MoneyChangeMapper moneyChangeMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerchantWalletMapper merchantWalletMapper;
    @Autowired
    private WxAliPayServiceImpl wxAliPayService;
    @Autowired
    private RemindMapper remindMapper;
    @Autowired
    private ICompanyMoneyChangService companyMoneyChangService;


    /**
     * 碰一碰代付回调
     */
    @RequestMapping(value = "/pypRePayment", method = RequestMethod.POST)
    @ResponseBody
    public void pypRePayment(HttpServletResponse response, HttpServletRequest request,
                             @RequestBody TreeMap<String, Object> json) {
        LOGGER.info("碰一碰代付订单异步通知：" + json.toString());
        // 异步通知参数封装
        TreeMap<String, Object> params = returnParam(response, request, json, "碰一碰消费订单异步通知");
        if (null == params) {
            return;
        }
        String orderNo = params.get("seria_no").toString();
        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderByOrderNo(orderNo);
        if (null == paymentOrder) {
            LOGGER.error("碰一碰代付订单异步通知，为查询到订单，订单编号==={}", orderNo);
            return;
        }
        if (paymentOrder.getOrderStatus().equals(1) || paymentOrder.getOrderStatus().equals(2)) {
            LOGGER.error("碰一碰代付订单异步通知，订单已回调，订单编号==={}", orderNo);
            return;
        }


        PaymentOrder paymentOrderNow = new PaymentOrder();
        paymentOrderNow.setId(paymentOrder.getId());
        paymentOrderNow.setIsNotify(1);
        paymentOrderNow.setCompleteTime(new Date());
        paymentOrderNow.setAcqReturnCode(params.get("res_code").toString());
        paymentOrderNow.setAcqReturnMsg(params.get("res_msg").toString());
        if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
            //1成功  2处理中  3失败
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                return;
            } else if ("2".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(0);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                return;
            } else {
                paymentOrderNow.setOrderStatus(2);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                return;
            }
        } else {
            paymentOrderNow.setOrderStatus(2);
            paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
            return;
        }


    }


    /**
     * 碰一碰消费订单异步通知
     */
    @RequestMapping(value = "/pypSaleOrder", method = RequestMethod.POST)
    @ResponseBody
    public void pypOrder(HttpServletResponse response, HttpServletRequest request,
                         @RequestBody TreeMap<String, Object> json) {
        LOGGER.info("碰一碰消费订单异步通知：" + json.toString());
        // 异步通知参数封装
        TreeMap<String, Object> params = returnParam(response, request, json, "碰一碰消费订单异步通知");
        if (null == params) {
            return;
        }
        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderByAcqOrderNo(params.get("seria_no").toString());
        if (null == paymentOrder) {
            //保存碰一碰订单
            paymentOrder = savePaymentOrder(params, PaymentOrderType.TWELVE.getCode());
        }
        paymentOrder.setAcqReturnCode(params.get("res_code").toString());
        paymentOrder.setAcqReturnMsg(params.get("res_msg").toString());
        paymentOrder.setCompleteTime(new Date());
        String orderStatus = params.get("status").toString();
        if ("1".equals(orderStatus)) {
            paymentOrder.setOrderStatus(1);
        } else if ("2".equals(orderStatus)) {
            paymentOrder.setOrderStatus(0);
        } else {
            paymentOrder.setOrderStatus(2);
        }
        paymentOrderMapper.updatePaymentOrder(paymentOrder);

        if (paymentOrder != null && paymentOrder.getOrderStatus().equals(1)) {
            if (paymentOrder.getAmountMoney().compareTo(BigDecimal.valueOf(10)) == 1) {
                //todo 成功之后开始分润
                moneyChangeService.commissions(paymentOrder.getId(), paymentOrder.getOrderType(),
                        paymentOrder.getAmountMoney(), paymentOrder.getMerchantId(), paymentOrder.getProfitMoney());
            }


            //成功之后发起提现
            PaymentOrder rePaymentOrder = savePaymentOrder(params, PaymentOrderType.THIRTEEN.getCode());
            String userId = params.get("user_id").toString();
            Merchant merchant = merchantMapper.selectMerchantByAcqMerchantNo(userId);
            try {
                JSONObject jsonObject = GuangGuUtil.pypRePayment(merchant, rePaymentOrder.getOrderNo(), merchant.getAcqMerchantNo(), rePaymentOrder.getAmountMoney(), rePaymentOrder.getRateMoney());
                if (jsonObject == null) {
                    rePaymentOrder.setAcqReturnMsg("上送异常");
                    rePaymentOrder.setOrderStatus(2);

                }
                if ("2".equals(jsonObject.getString("status")) && "SUCCESS".equals(jsonObject.getString("ret_code")) && "YQB000000".equals(jsonObject.getString("res_code"))) {
                    rePaymentOrder.setOrderStatus(0);
                    rePaymentOrder.setAcqReturnCode(jsonObject.getString("res_code"));
                    rePaymentOrder.setAcqReturnMsg(jsonObject.getString("res_msg"));
                    rePaymentOrder.setAcqOrderNo(jsonObject.getString("seria_no"));
                } else {
                    rePaymentOrder.setAcqReturnMsg(jsonObject.getString("res_msg"));
                    rePaymentOrder.setOrderStatus(2);
                }
                paymentOrderMapper.updatePaymentOrder(rePaymentOrder);
            } catch (Exception e) {
                LOGGER.error("上送碰一碰代付异常{}", e);
                rePaymentOrder.setAcqReturnMsg(e.toString());
                rePaymentOrder.setOrderStatus(2);
                paymentOrderMapper.updatePaymentOrder(rePaymentOrder);
            }

        }

    }

    private PaymentOrder savePaymentOrder(TreeMap<String, Object> params, Integer orderType) {
        PaymentOrder order = new PaymentOrder();
        String userId = params.get("user_id").toString();
        Merchant merchant = merchantMapper.selectMerchantByAcqMerchantNo(userId);
        order.setMerchantId(merchant.getId());
        order.setMerchantName(merchant.getMerchantCnName());
        order.setId(StringUtils.randomUUID());
        order.setOrderNo(StringUtils.createNum());
        //12=碰一碰消费,13=碰一碰代付
        order.setOrderType(orderType);
        order.setAmountMoney(new BigDecimal(params.get("trade_amount").toString()));

        String rateStr = "";
        try {
            // 从redis中取
            rateStr = RedisPoolUtil.get("rate");
        } catch (Exception e) {
            rateStr = "nil";
        }
        if (rateStr == null || "".equals(rateStr) || "nil".equals(rateStr)) {
            // 查询全局配置获取平台费率
            SystemConfig config = configMapper.selectSystemConfigByConfigCode(SystemConfigCode.RATE.getCode());
            try {
                // 保存到缓存中
                RedisPoolUtil.setex("rate", config.getConfigValue(), 86400);
            } catch (Exception e) {
            }
            rateStr = config.getConfigValue();
        }
        JSONObject rateJson = JSONObject.parseObject(rateStr);


        if (orderType.equals(13)) {
            order.setOrderStatus(0);
            BigDecimal pypPro = BigDecimal.ZERO;
            if (new BigDecimal("1000").compareTo(order.getAmountMoney()) == 0 || new BigDecimal("1000").compareTo(order.getAmountMoney()) == 1) {
                pypPro = new BigDecimal(rateJson.getString("pypmin").split("\\+")[1]);
            } else {
                pypPro = new BigDecimal(rateJson.getString("pypmax").split("\\+")[1]);
            }
            order.setRateMoney(pypPro);
        }


        order.setClearingStatus(1);

        if (orderType.equals(12)) {
            order.setCompleteTime(new Date());
            String bankAccountNo = null;
            try {
                bankAccountNo = EncryptUtil.desDecrypt(params.get("bank_card_no").toString(), GuangGuConfig.keys);
            } catch (Exception e) {
                e.printStackTrace();
            }
            BigDecimal rate;
            BigDecimal pro;
            if (new BigDecimal("1000").compareTo(order.getAmountMoney()) == 0 || new BigDecimal("1000").compareTo(order.getAmountMoney()) == 1) {
                rate = new BigDecimal(rateJson.getString("pypmin").split("\\+")[0]);
                pro = new BigDecimal(rateJson.getString("pypmin").split("\\+")[1]);
            } else {
                rate = new BigDecimal(rateJson.getString("pypmax").split("\\+")[0]);
                pro = new BigDecimal(rateJson.getString("pypmax").split("\\+")[1]);
            }

            order.setProfitMoney(order.getTotalMoney().multiply(rate).add(pro).setScale(2, BigDecimal.ROUND_UP));
            order.setCreditNumber(bankAccountNo);
            order.setAcqReturnCode(params.get("res_code").toString());
            order.setAcqReturnMsg(params.get("res_msg").toString());
            order.setAcqOrderNo(params.get("order_no").toString());
            order.setIsNotify(1);
            order.setClearingStatus(1);
            String orderStatus = params.get("status").toString();
            if ("1".equals(orderStatus)) {
                order.setOrderStatus(1);
            } else if ("2".equals(orderStatus)) {
                order.setOrderStatus(0);
            } else {
                order.setOrderStatus(2);
            }
        }

        paymentOrderMapper.insertPaymentOrder(order);
        return order;
    }


    /**
     * 境外消费订单异步通知
     */
    @RequestMapping(value = "/abroadOrderPay", method = RequestMethod.POST)
    @ResponseBody
    public void abroadOrderPay(HttpServletResponse response, HttpServletRequest request,
                               @RequestBody TreeMap<String, Object> json) {
        LOGGER.info("境外消费订单异步通知：" + json.toString());
        // 异步通知参数封装
        TreeMap<String, Object> params = returnParam(response, request, json, "境外消费订单异步通知");
        if (params == null) {
            return;
        }

        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderByOrderNo(params.get("seria_no").toString());
        if (paymentOrder == null) {
            LOGGER.info("光谷【境外消费订单异步通知】成功，查询订单未结果，订单号：{}", params.get("seria_no").toString());
            return;
        }
        //10 境外消费
        if (paymentOrder.getOrderStatus().equals(0) && paymentOrder.getOrderType().equals(PaymentOrderType.TEN.getCode())) {
            PaymentOrder paymentOrderNow = new PaymentOrder();
            paymentOrderNow.setId(paymentOrder.getId());
            paymentOrderNow.setIsNotify(1);
            paymentOrderNow.setCompleteTime(new Date());
            paymentOrderNow.setAcqReturnCode(params.get("res_code").toString());
            paymentOrderNow.setAcqReturnMsg(params.get("res_msg").toString());
            Merchant merchant = merchantMapper.selectMerchantById(paymentOrder.getMerchantId());
            // 1成功 2处理中 3失败
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                //分润
                wxAliPayService.orderProfit(paymentOrder, merchant.getPhone());
            } else {
                paymentOrderNow.setOrderStatus(2);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
            }
        }
    }


    /**
     * 提现回调
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "/withdrawal", method = RequestMethod.POST)
    @ResponseBody
    public void repaymentMch(HttpServletResponse response, HttpServletRequest request,
                             @RequestBody TreeMap<String, Object> json) {
        LOGGER.info("提现异步回调：" + json.toString());
        // 异步通知参数封装
        TreeMap<String, Object> params = returnParam(response, request, json, "提现回调");
        if (params == null) {
            return;
        }
        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderByOrderNo(params.get("seria_no").toString());
        if (paymentOrder == null) {
            LOGGER.info("光谷【提现回调】成功，查询订单未结果，订单号：{}", params.get("seria_no").toString());
            return;
        }
        // 订单类型（0 无卡消费 1养卡消费 2养卡代付3无卡出款4退款5提现 6充值升级）
        if (paymentOrder.getOrderStatus().equals(0) && paymentOrder.getOrderType().equals(5)) {
            PaymentOrder paymentOrderNow = new PaymentOrder();
            paymentOrderNow.setId(paymentOrder.getId());
            paymentOrderNow.setIsNotify(1);
            paymentOrderNow.setCompleteTime(new Date());
            paymentOrderNow.setAcqReturnCode(params.get("res_code").toString());
            paymentOrderNow.setAcqReturnMsg(params.get("res_msg").toString());
            if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
                // 1成功 2处理中 3失败
                if ("1".equals(params.get("status"))) {
                    paymentOrderNow.setOrderStatus(1);
                    paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                    merchantWalletMapper.withdrawalSuccess(paymentOrder.getMerchantId(), paymentOrder.getAmountMoney());
                    // 修改提现记录状态
                    List<MoneyChange> moneyChangeList = moneyChangeMapper.selectMoneyChangeByOrderIdAndMoneyType(
                            paymentOrderNow.getId(), MoneyTypeStatus.F.getCode());
                    if (moneyChangeList != null && moneyChangeList.size() > 0) {
                        MoneyChange moneyChange = moneyChangeList.get(0);
                        moneyChange.setStatus("10C");
                        moneyChangeMapper.updateMoneyChange(moneyChange);
                    }
                    moneyChangeService.withdrawal(paymentOrder);
                } else {
                    paymentOrderNow.setOrderStatus(2);
                    // 失败之后 返回用余额，修改用户提现记录状态
                    // 修改分润记录状态
                    List<MoneyChange> moneyChangeList = moneyChangeMapper.selectMoneyChangeByOrderIdAndMoneyType(
                            paymentOrderNow.getId(), MoneyTypeStatus.F.getCode());
                    if (moneyChangeList != null && moneyChangeList.size() > 0) {
                        MoneyChange moneyChange = moneyChangeList.get(0);
                        moneyChange.setStatus("10D");
                        moneyChangeMapper.updateMoneyChange(moneyChange);
                    }
                    // 修改用户账户余额
                    merchantWalletMapper.withdrawalFail(paymentOrder.getMerchantId(), paymentOrder.getAmountMoney());
                }
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
            }
        }

    }

    /**
     * 出款异步回调
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "/payment", method = RequestMethod.POST)
    @ResponseBody
    public void payment(HttpServletResponse response, HttpServletRequest request,
                        @RequestBody TreeMap<String, Object> json) {
        LOGGER.info("出款异步回调：" + json.toString());
        // 异步通知参数封装
        TreeMap<String, Object> params = returnParam(response, request, json, "出款回调");
        if (params == null) {
            return;
        }
        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderByOrderNo(params.get("seria_no").toString());
        if (paymentOrder == null) {
            LOGGER.info("光谷【出款异步回调】成功，查询订单未结果，订单号：{}", params.get("seria_no").toString());
            return;
        }
        // 订单类型（0 无卡消费 1养卡消费 2养卡代付3无卡出款4退款5提现 6充值升级）
        if (paymentOrder.getOrderStatus().equals(0)) {
            PaymentOrder paymentOrderNow = new PaymentOrder();
            paymentOrderNow.setId(paymentOrder.getId());
            paymentOrderNow.setIsNotify(1);
            paymentOrderNow.setCompleteTime(new Date());
            paymentOrderNow.setAcqReturnCode(params.get("res_code").toString());
            paymentOrderNow.setAcqReturnMsg(params.get("res_msg").toString());
            paymentOrderNow.setCreditNumber(paymentOrder.getCreditNumber());
            paymentOrderNow.setClearingStatus(paymentOrder.getClearingStatus());
            paymentOrderNow.setAmountMoney(paymentOrder.getAmountMoney());
            paymentOrderNow.setProfitMoney(paymentOrder.getProfitMoney());
            paymentOrderNow.setMerchantId(paymentOrder.getMerchantId());
            if (paymentOrder.getOrderType().equals(2) || paymentOrder.getOrderType().equals(8)) {
                // 2养卡代付
                paymentYK(paymentOrderNow, params);
            } else if (paymentOrder.getOrderType().equals(3)) {
                // 3无卡出款
                paymentWK(paymentOrderNow, params);
            } else if (paymentOrder.getOrderType().equals(4)) {
                // 退款 回调
                paymentOrderRefund(paymentOrderNow, params);
            } else {
                LOGGER.info("光谷【出款异步回调】，订单类型未匹配，订单ID{}", params.get("seria_no").toString());
                return;
            }
        }

    }

    /**
     * 退款 回调处理
     *
     * @param paymentOrderNow
     * @param params
     */
    private void paymentOrderRefund(PaymentOrder paymentOrderNow, TreeMap<String, Object> params) {

        if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
            // 1成功 2处理中 3失败
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                return;
            } else if ("2".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(0);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                return;
            } else {
                paymentOrderNow.setOrderStatus(2);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
            }
        } else {
            paymentOrderNow.setOrderStatus(2);
            paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
        }

    }

    /**
     * 消费异步通知
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "/sale", method = RequestMethod.POST)
    @ResponseBody
    public void sale(HttpServletResponse response, HttpServletRequest request,
                     @RequestBody TreeMap<String, Object> json) {
        LOGGER.info("消费异步回调：" + json.toString());
        // 异步通知参数封装
        TreeMap<String, Object> params = returnParam(response, request, json, "消费回调");
        if (params == null) {
            return;
        }
        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderByOrderNo(params.get("seria_no").toString());
        if (paymentOrder == null) {
            LOGGER.info("光谷【消费异步回调】，查询订单未结果，订单号：{}", params.get("seria_no").toString());
            return;
        }
        if (paymentOrder.getOrderStatus().equals(0)) {
            PaymentOrder paymentOrderNow = new PaymentOrder();
            paymentOrderNow.setId(paymentOrder.getId());
            paymentOrderNow.setIsNotify(1);
            paymentOrderNow.setCompleteTime(new Date());
            // 1：成功 2:处理中 3:失败 4:清算异常 0 预处理
            // 订单状态（0处理中 1成功 2失败3已补单 9回 ）
            paymentOrderNow.setAcqReturnCode(params.get("res_code").toString());
            paymentOrderNow.setAcqReturnMsg(params.get("res_msg").toString());
            paymentOrderNow.setMerchantId(paymentOrder.getMerchantId());
            if (paymentOrder.getOrderType() == 0) {
                // 无卡
                saleWK(paymentOrderNow, paymentOrder, params);
                // 养卡消费
            } else if (paymentOrder.getOrderType() == 1 || paymentOrder.getOrderType().equals(7)) {
                saleYK(paymentOrderNow, paymentOrder, params);
            } else if (paymentOrder.getOrderType().equals(11)) {
                // 快捷无卡
                quickWK(paymentOrderNow, paymentOrder, params);
            } else {
                LOGGER.info("光谷【消费异步回调】，订单类型未匹配，订单ID{}", params.get("seria_no").toString());
                return;
            }
        }

    }

    private void quickWK(PaymentOrder paymentOrderNow, PaymentOrder paymentOrder, TreeMap<String, Object> params) {
        // TODO Auto-generated method stub
        if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                if (paymentOrder.getClearingStatus().equals(0)) {
                    // 清分
                    moneyChangeService.commissions(paymentOrder.getId(), paymentOrder.getOrderType(),
                            paymentOrder.getAmountMoney(), paymentOrder.getMerchantId(), paymentOrder.getProfitMoney());
                    releaseVipMoney(paymentOrderNow);
                }
                return;
            }
        }
        paymentOrderNow.setOrderStatus(2);
        paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
        return;
    }


    /**
     * 养卡消费异步处理
     *
     * @param paymentOrderNow
     * @param params
     */
    private void saleYK(PaymentOrder paymentOrderNow, PaymentOrder paymentOrder, TreeMap<String, Object> params) {
        PlanItemNew planItemNew = planItemNewMapper.selectPlanItemNewListByOrderId(paymentOrderNow.getId());
        if (planItemNew == null) {
            LOGGER.error("养卡消费获取小计划信息失败，订单ID=" + paymentOrderNow.getId());
            return;
        }
        PlanItemNew planItemNewNow = new PlanItemNew();
        planItemNewNow.setId(planItemNew.getId());

        PlanNew planNew = planNewMapper.selectPlanNewById(planItemNew.getPlanId());
        if (planNew == null) {
            LOGGER.error("养卡消费获取大计划信息失败，大计划ID=" + planItemNew.getPlanId());
            return;
        }
        PlanNew planNewNow = new PlanNew();
        planNewNow.setId(planNew.getId());
        if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                if (paymentOrder.getClearingStatus().equals(0)) {
                    // 清分
                    moneyChangeService.commissions(paymentOrder.getId(), paymentOrder.getOrderType(),
                            paymentOrder.getAmountMoney(), paymentOrder.getMerchantId(), paymentOrder.getProfitMoney());
                }
                // 修改计划信息
                planItemNewNow.setStatus(3);
                planItemNewNow.setUpdateTime(new Date());
                planItemNewMapper.updatePlanItemNew(planItemNewNow);
                if (planNew.getType().equals(5) && planItemNew.getGroupNumber().equals(planNew.getMaxGroupNum())
                        && PlanItemType.SALE.getCode().equals(planItemNew.getMoneyType())) {
                    //全额消费
                    planNewNow.setUpdateTime(new Date());
                    planNewNow.setStatus(3);
                    planNewMapper.updatePlanNew(planNewNow);
                    // 根据商户id查询商户信息
                    Merchant merchant = merchantMapper.selectMerchantById(planNew.getMerchantId());
                    if (StringUtils.isNotNull(merchant)) {
                        Map<String, String> map = new HashMap<>(3);
                        map.put("user_phone", merchant.getReservePhone());
                        // 发送内容
                        String number = planItemNew.getCardNumber();
                        number = number.substring(number.length() - 4, number.length());
                        String context = "你尾号为:" + number + "的银行卡本期计划已完成请您知悉。";
                        map.put("content", context);
                        map.put("sendType", SMSTemplateType.NOTICE.getCode());
                        try {
                            JSONObject gg = GuangGuUtil.smsPackage(map);
                            String resCode = gg.getString("res_code");
                            if (("YQB000000").equals(resCode)) {
                                LOGGER.info("【计划订单】计划订单短信通知计划完成发送成功！");
                            } else {
                                LOGGER.info("【计划订单】计划订单短信通知计划完成发送失败！");
                            }
                        } catch (Exception e) {
                            LOGGER.info("【计划订单】计划订单短信通知计划完成发送失败！");
                        }
                    }
                }

                return;
            }
        }
        paymentOrderNow.setOrderStatus(2);
        paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
        // 失败之后 修改计划信息
        planItemNewNow.setStatus(2);
        planItemNewNow.setUpdateTime(new Date());
        planNewNow.setStatus(2);
        planNewNow.setUpdateTime(new Date());
        planNewMapper.updatePlanNew(planNewNow);
        planItemNewMapper.updatePlanItemNew(planItemNewNow);
        sendMsg(planNewNow.getId());
        return;
    }

    /**
     * 异步处理无卡消费订单
     *
     * @param paymentOrderNow
     * @param params
     */
    private void saleWK(PaymentOrder paymentOrderNow, PaymentOrder paymentOrder, TreeMap<String, Object> params) {
        if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                int claerStutas = paymentOrder.getClearingStatus();
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                if (claerStutas == 0) {
                    // 清分
                    moneyChangeService.commissions(paymentOrder.getId(), paymentOrder.getOrderType(),
                            paymentOrder.getAmountMoney(), paymentOrder.getMerchantId(), paymentOrder.getProfitMoney());
                }
                // 无卡出款
                acqService.guangGuOut(paymentOrder, paymentOrder.getMerchantId());
                return;
            }
        }
        paymentOrderNow.setOrderStatus(2);
        paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
        return;
    }

    /**
     * 无卡出款
     *
     * @param paymentOrderNow
     * @param params
     */
    private void paymentWK(PaymentOrder paymentOrderNow, TreeMap<String, Object> params) {
        if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
            // 1成功 2处理中 3失败
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                releaseVipMoney(paymentOrderNow);
                return;
            } else if ("2".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(0);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
            } else {
                paymentOrderNow.setOrderStatus(2);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                return;
            }
        } else {
            paymentOrderNow.setOrderStatus(2);
            paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
            return;
        }
    }

    /**
     * 养卡代付
     *
     * @param paymentOrderNow
     * @param params
     */
    private void paymentYK(PaymentOrder paymentOrderNow, TreeMap<String, Object> params) {
        PlanItemNew planItemNew = planItemNewMapper.selectPlanItemNewListByOrderId(paymentOrderNow.getId());
        if (planItemNew == null) {
            LOGGER.error("养卡代付获取小计划信息失败，订单ID=" + paymentOrderNow.getId());
            return;
        }
        PlanItemNew planItemNewNow = new PlanItemNew();
        planItemNewNow.setId(planItemNew.getId());
        PlanNew planNew = planNewMapper.selectPlanNewById(planItemNew.getPlanId());
        if (planNew == null) {
            LOGGER.error("养卡代付获取大计划信息失败，大计划ID=" + planItemNew.getPlanId());
            return;
        }
        PlanNew planNewNow = new PlanNew();
        planNewNow.setId(planNew.getId());
        if ("SUCCESS".equals(params.get("ret_code")) && "YQB000000".equals(params.get("res_code"))) {
            // 1成功 2处理中 3失败
            if ("1".equals(params.get("status"))) {
                paymentOrderNow.setOrderStatus(1);
                paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
                // 修改计划信息
                planItemNewNow.setStatus(3);
                planItemNewNow.setUpdateTime(new Date());
                planItemNewMapper.updatePlanItemNew(planItemNewNow);
                List<Remind> remindList = remindMapper.selctRemindByCardId(planItemNew.getCardId());
                if (remindList != null && remindList.size() > 0) {
                    Remind r = remindList.get(0);
                    r.setPaymentMoney(r.getPaymentMoney().add(paymentOrderNow.getAmountMoney()));
                    remindMapper.updateRemind(r);
                }
                if (!planNew.getType().equals(5)) {
                    if (planItemNew.getGroupNumber().equals(planNew.getMaxGroupNum())
                            && PlanItemType.PAYMENT.getCode().equals(planItemNew.getMoneyType())) {
                        // 判断是否是最后一条计划
                        planNewNow.setUpdateTime(new Date());
                        planNewNow.setStatus(3);
                        planNewMapper.updatePlanNew(planNewNow);
                        // 根据商户id查询商户信息
                        Merchant merchant = merchantMapper.selectMerchantById(planNew.getMerchantId());
                        if (StringUtils.isNotNull(merchant)) {
                            Map<String, String> map = new HashMap<>(3);
                            map.put("user_phone", merchant.getReservePhone());
                            // 发送内容
                            String number = paymentOrderNow.getCreditNumber();
                            number = number.substring(number.length() - 4, number.length());
                            String context = "你尾号为:" + number + "的银行卡本期计划已完成请您知悉。";
                            map.put("content", context);
                            map.put("sendType", SMSTemplateType.NOTICE.getCode());
                            try {
                                JSONObject gg = GuangGuUtil.smsPackage(map);
                                String resCode = gg.getString("res_code");
                                if (("YQB000000").equals(resCode)) {
                                    LOGGER.info("【计划订单】计划订单短信通知计划完成发送成功！");
                                } else {
                                    LOGGER.info("【计划订单】计划订单短信通知计划完成发送失败！");
                                }
                            } catch (Exception e) {
                                LOGGER.info("【计划订单】计划订单短信通知计划完成发送失败！");
                            }
                        }
                    }

                }
                if (paymentOrderNow.getClearingStatus().equals(0)) {
                    // 清分
                    paymentOrderMapper.updateOrderStatusAndClearingStatus(paymentOrderNow.getId(), 1, 1);
                }
                return;
            }
        }
        paymentOrderNow.setOrderStatus(2);
        paymentOrderMapper.updatePaymentOrder(paymentOrderNow);
        // 失败之后 修改计划信息
        planItemNewNow.setStatus(2);
        planItemNewNow.setUpdateTime(new Date());
        planNewNow.setStatus(2);
        planNewNow.setUpdateTime(new Date());
        planNewMapper.updatePlanNew(planNewNow);
        planItemNewMapper.updatePlanItemNew(planItemNewNow);
        sendMsg(planNewNow.getId());
    }

    /**
     * 异步回调 参数封装
     *
     * @param response
     * @param request
     * @param json
     * @param type
     * @return
     */
    private TreeMap<String, Object> returnParam(HttpServletResponse response, HttpServletRequest request,
                                                TreeMap<String, Object> json, String type) {
        PrintWriter p = null;
        try {
            p = response.getWriter();
            p.write("success");
            p.flush();
        } catch (Exception e) {
            LOGGER.info("光谷【{}", type + "】异常：" + response.toString());
        } finally {
            if (p != null) {
                p.close();
            }
        }
        if (request == null) {
            LOGGER.info("光谷【{}", type + "】成功，但未返回信息：{}", request == null ? request : request.toString());
            return null;
        }
        String sign = SignUtil.sign(json, GuangGuConfig.keys);
        if (!json.get("sign").equals(sign)) {
            LOGGER.info("光谷【{}", type + "】签名校验失败：{}", json);
            return null;
        }
        return json;
    }

    private void sendMsg(String planId) {
        // 短信通知
        try {
            String context = "计划ID:" + planId + "的计划失败，因为存在执行中带回调的计划。请及时处理！";
            Map<String, String> map = new HashMap<>(3);
            // 手机号

            String sendPhone = "";
            try {
                sendPhone = RedisPoolUtil.get("sendPhone");
            } catch (Exception e) {
                sendPhone = "nil";
            }
            if (sendPhone == null || "".equals(sendPhone) || "nil".equals(sendPhone)) {
                SystemConfig config = configMapper
                        .selectSystemConfigByConfigCode(SystemConfigCode.SEND_PHONE.getCode());
                try {
                    // 保存到缓存中
                    RedisPoolUtil.setex("sendPhone", config.getConfigValue(), 86400);
                } catch (Exception e) {
                }
                sendPhone = config.getConfigValue();
            }
            map.put("user_phone", sendPhone);
            // 发送内容
            map.put("content", context);
            map.put("sendType", SMSTemplateType.NOTICE.getCode());
            JSONObject gg = GuangGuUtil.smsPackage(map);
            String resCode = gg.getString("res_code");
            if (("YQB000000").equals(resCode)) {
                LOGGER.info("【异步回调】计划短信通知发送成功！");
            }
        } catch (Exception e) {
            LOGGER.error("【异步回调】计划短信通知发送失败！", e);
        }
    }


    /**
     * vip补贴笔数费释放
     *
     * @param paymentOrderNow
     */
    public void releaseVipMoney(PaymentOrder paymentOrderNow) {
        MerchantWallet mw = merchantWalletMapper.selectMerchantWalletByMerId(paymentOrderNow.getMerchantId());
        if (mw.getVipMoney().compareTo(BigDecimal.ZERO) == 1) {
            Integer num = mw.getSkNum() + 1;
            MerchantWallet mwNum = new MerchantWallet();
            mwNum.setId(mw.getId());
            mwNum.setSkNum(num);
            mwNum.setReleaseVipMoney(mw.getReleaseVipMoney().add(BigDecimal.valueOf(2)));
            mwNum.setVipMoney(mw.getVipMoney().subtract(BigDecimal.valueOf(2)));
            mwNum.setBalanceMoney(mw.getBalanceMoney().add(BigDecimal.valueOf(2)));
            mwNum.setTotalMoney(mw.getTotalMoney().add(BigDecimal.valueOf(2)));
            mwNum.setProfit(mw.getProfit().add(BigDecimal.valueOf(2)));
            mwNum.setProfitMoth(mw.getProfitMoth().add(BigDecimal.valueOf(2)));
            merchantWalletMapper.updateMerchantWallet(mwNum);
            MoneyChange m = new MoneyChange();
            m.setCreateTime(new Date());
            m.setId(StringUtils.randomUUID());
            m.setMoneyType("10Z");
            m.setPaymentOrderId(paymentOrderNow.getId());
            m.setStatus("10C");
            m.setUserId(paymentOrderNow.getMerchantId());
            m.setTrxAmt(BigDecimal.valueOf(2));
            moneyChangeMapper.insertMoneyChange(m);
            //推送
            try {
                pushAll(paymentOrderNow.getMerchantId(), "2");
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("极光推送失败,{}",e);
            }
        }
    }

    /**
     * 公司入账记录添加
     *
     * @param profitMoney
     * @param hashMoney
     * @param orderId
     */
    public void compayMoney(BigDecimal profitMoney, BigDecimal hashMoney, String orderId) {
        CompanyMoneyChang moneyChang = new CompanyMoneyChang();
        moneyChang.setId(StringUtils.randomUUID());
        moneyChang.setEntryMoney(profitMoney);
        moneyChang.setProfitMoney(hashMoney);
        moneyChang.setMoney(profitMoney.subtract(hashMoney).setScale(3, BigDecimal.ROUND_DOWN));
        moneyChang.setOrderId(orderId);
        moneyChang.setCreateTime(new Date());
        companyMoneyChangService.insertCompanyMoneyChang(moneyChang);
    }


    /**
     * 分润推送
     */
    protected void pushAll(String merchantId, String money) {
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        String name = merchant.getMerchantCnName().substring(0, 1);
        merchantMapper.selectMerchantById(merchantId);
        Map<String, String> parm = new HashMap<String, String>(16);
        parm.put("id", merchant.getMerchantNo());
        parm.put("msg", name + "**" + ",vip补贴笔数费释放" + money);
        parm.put("dateTime", DateUtils.getTime());
        JPushUtil.jpushAll(parm);
    }


}
